#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2022/10/19 15:11
# file: user.py
# author: lotus163
from typing import Optional

from fastapi import APIRouter, Depends

from backend.core.deps import UserDepends, get_user_depends
from backend.core.result import Result, result_success, ResultList, ResultData
from backend.crud import NoticeDao
from backend.schemas import SysNoticeAdd, SysNoticeSch
from backend.utils.form_util import get_form_dict
from backend.utils.string_util import get_array_by_str

router = APIRouter(prefix="/notice", tags=["公告"])


@router.put("", response_model=Result, summary='修改公告')
async def update_notice(form: SysNoticeSch, user_depends: UserDepends = Depends(get_user_depends)):
    notice_db = await NoticeDao.get_db_or_none(noticeId=form.noticeId)
    # 添加创建者
    form.updateBy = user_depends.login_user.user.userName
    await NoticeDao.update_sch(obj=notice_db, **form.dict(exclude_none=True))
    return result_success()


@router.post("", response_model=Result, summary='新增公告')
async def add_notice(form: SysNoticeAdd, user_depends: UserDepends = Depends(get_user_depends)):
    form.createBy = user_depends.login_user.user.userName
    await NoticeDao.add_sch(**form.dict(exclude_none=True))
    return result_success()


@router.get("/list", response_model=ResultList[SysNoticeSch], summary='获取公告列表')
async def get_notices_list(pageNum: int, pageSize: int,
                           noticeTitle: Optional[str] = None,
                           createBy: Optional[str] = None,
                           noticeType: Optional[int] = None,
                           user_depends: UserDepends = Depends(get_user_depends)):
    # 时间
    start, end = user_depends.request_service.get_params_time()
    # 准备查询的参数
    form_dict = get_form_dict(form=SysNoticeSch(noticeTitle=noticeTitle, createBy=createBy, noticeType=noticeType),
                              start=start, end=end, time_range="createTime__range")
    # 查询
    notices_sch = await NoticeDao.get_list_sch_page(pageSize=pageSize, pageNum=pageNum, **form_dict)
    total = await NoticeDao.get_list_count(**form_dict)
    return result_success(msg="查询成功", rows=notices_sch, total=total)


@router.delete("/{noticeIds}", response_model=Result, summary='根据ids删除公告')
async def remove_notices(noticeIds: str, user_depends: UserDepends = Depends(get_user_depends)):
    await NoticeDao.delete_db(noticeId__in=get_array_by_str(noticeIds))
    return result_success()


@router.get("/{noticeId}", response_model=ResultData, summary='根据id获取详细公告')
async def get_notice_info(noticeId: int, user_depends: UserDepends = Depends(get_user_depends)):
    notice_sch = await NoticeDao.get_sch_or_none(noticeId=noticeId)
    return result_success(data=notice_sch)
